package com.atguigu.rabbit.consumer.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class Consumer01Listener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "manual_test_01", durable = "true"),
            exchange = @Exchange(value = "manual_test_01", durable = "true", type = ExchangeTypes.DIRECT),
            key = "manual_test"
    ))
    public void a(Channel channel, Message message, String str) {
        try {
            System.out.println("=================Consumer01Listener==============");
            byte[] body = message.getBody();
            String msg = new String(body);
            System.out.println(str + "  " + msg);
            System.out.println("=================Consumer01Listener==============");

            long deliveryTag = message.getMessageProperties().getDeliveryTag(); // 初始为1，每次确认消息时，deliveryTag加1
            Object id = message.getMessageProperties().getHeader("spring_returned_message_correlation");
             //int i = 1 / 0;
            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            System.out.println("消息ID: " + id);
            System.out.println("消息已确认，deliveryTag: " + deliveryTag);

        } catch (Exception e) {
            System.err.println("处理消息时发生异常: " + e.getMessage());
            try {
                long deliveryTag = message.getMessageProperties().getDeliveryTag();
                // 发生异常时拒绝消息并重新入队,下次服务开启时候自动处理回滚后的消息  此时会无线重试
                channel.basicNack(deliveryTag, true, true);
                System.out.println("消息已拒绝并重新入队");
            } catch (IOException ioException) {
                System.err.println("确认消息失败: " + ioException.getMessage());
            }
        }
    }
}
